package com.lhframework.sms.api;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.common.base.Strings;
import com.lhframework.sms.model.ShortMessage;
import com.lhframework.sms.service.ShortMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * Created by lh on 2017/8/1.
 *
 */
@Component
public class TimingSmsSender extends AbstractSmsSender {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ShortMessageService shortMessageService;

    @Override
    public SendSmsResponse send(String phone, String templateName, String templateCode, ShortMessage.Type type, Map<String, String> params) {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        logger.info("短信发送（手机号：" + phone + "，模板名：" + templateName + "，模板code：" + templateCode + "，短信类型：" + type.getValue() + "，参数：" + JSON.toJSONString(params) + "）");

        try {
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phone);
            request.setSignName(signature);
            request.setTemplateCode(templateCode);
            request.setTemplateParam(JSON.toJSONString(params));
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

            //短信入库
            ShortMessage shortMessage = new ShortMessage();
            shortMessage.setPhone(phone);
            String content = "";
            content = environment.getProperty(templateName);
            for (Map.Entry<String, String> param : params.entrySet()) {
                content = content.replaceFirst("\\{" + param.getKey() + "\\}", param.getValue());
            }
            shortMessage.setContent(content);
            shortMessage.setType(type);
            shortMessage.setTemplateName(templateName);
            shortMessage.setTemplateCode(templateCode);
            shortMessage.setParams(JSON.toJSONString(params));
            shortMessage.setTimeType(ShortMessage.TimeType.TIMING);
            if (sendSmsResponse != null) {
                //记录发送状态
                boolean sendSuccess = sendSmsResponse.getCode().equalsIgnoreCase("OK");
                shortMessage.setStatus(sendSuccess ? ShortMessage.Status.SUCCESS : ShortMessage.Status.FAILURE);
                //记录阿里返回结果
                shortMessage.setRemark(JSON.toJSONString(sendSmsResponse));
            }
            shortMessage.setUpdatedTime(new Date());
            shortMessageService.add(shortMessage);
            return sendSmsResponse;
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    public SendSmsResponse send(ShortMessage shortMessage) {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        logger.info("短信发送（手机号：" + shortMessage.getPhone() + "，模板名：" + shortMessage.getTemplateName() + "，模板code：" + shortMessage.getTemplateCode() + "，短信类型：" + shortMessage.getType().getValue() + "）");

        try {
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(shortMessage.getPhone());
            request.setSignName(signature);
            request.setTemplateCode(shortMessage.getTemplateCode());
            if (!Strings.isNullOrEmpty(shortMessage.getParams())) {
                request.setTemplateParam(shortMessage.getParams());
                String content = "";
                content = environment.getProperty(shortMessage.getTemplateName());
                Map<String, String> params = JSON.parseObject(shortMessage.getParams(), Map.class);
                for (Map.Entry<String, String> param : params.entrySet()) {
                    content = content.replaceFirst("\\{" + param.getKey() + "\\}", param.getValue());
                }
                shortMessage.setContent(content);
            }
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

            //短信入库
            if (sendSmsResponse != null) {
                //记录发送状态
                boolean sendSuccess = sendSmsResponse.getCode().equalsIgnoreCase("OK");
                shortMessage.setStatus(sendSuccess ? ShortMessage.Status.SUCCESS : ShortMessage.Status.FAILURE);
                //记录阿里返回结果
                shortMessage.setRemark(JSON.toJSONString(sendSmsResponse));
            }
            shortMessage.setUpdatedTime(new Date());
            shortMessageService.update(shortMessage);
            return sendSmsResponse;
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
}
